import { request } from "../../request/index.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj:{}
  },

  // 商品对象
  GoodsInfo:{},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      const {goods_id}=options;
      this.getGoodsDetail(goods_id);
      // console.log(goods_id);
      
  },

  async getGoodsDetail(goods_id){
    const goodsObj=await request({url:"/goods/detail",data:{goods_id}});
    // console.log(res);
    this.GoodsInfo=goodsObj;
    this.setData({
      goodsObj:{
        goods_name:goodsObj.goods_name,
        goods_price:goodsObj.goods_price,
        // iPhone不识别webp 临时自己改webp->jpg
        goods_introduce:goodsObj.goods_introduce.replace(/\.webp/g,'.jpg'),
        pics:goodsObj.pics
      }
    })
    
  },

  handlePreviewImage(e){
    const urls=this.GoodsInfo.pics.map(v=>v.pics_mid) ;
    const current=e.currentTarget.dataset.url;
    wx.previewImage({
      urls,
      current
    })
    
  },

  handleCartAdd(){
    // console.log("addCart");
    // 获取缓存中的购物车数组，第一次空确保是数组格式
    let cart=wx.getStorageSync("cart")||[];
    // 判断商品是否在数组中
    let index=cart.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id)
    
    if(index===-1){
      // 不存在
      this.GoodsInfo.num=1;
      this.GoodsInfo.checked=true;
      cart.push(this.GoodsInfo)
    }else{
      //已经存在执行NUM++ 
      cart[index].num++;
    }

    // 把购物车添加回缓存中
    wx.setStorageSync("cart", cart);

    // 弹窗提示
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true,
    });
      
      
  }

})